<template>
  <div style="padding-bottom:30px">
    <div v-if="isPageLoading" class="page_loading fixed">
      <van-loading size="24px" vertical color="#fff">加载中...</van-loading>
    </div>
    <header>
      <van-nav-bar class="main_header notice_header" :title="title">
        <template #left>
          <span @click="goBack">返回</span>
        </template>
      </van-nav-bar>
    </header>
    <div class="gl_mt_10 gl_mx_10 order">
      <div class="order_img">
        <img v-if="orderData.pathImages" :src="getStaticFileUrl(orderData.pathImages)" alt="" style="width:100%;height:100%">
      </div>
      <div class="order_text gl_ml_15">
        <div class="space_between">
          <div class="gl_ft_weight order_name">{{ orderData.name }}</div>
          <div class="order_span gl_ml_20">
            <span v-if="orderData.orderStatusCode" class="content">
              <template v-for="ktem in dict.orderStatus">
                {{ ktem.code === orderData.orderStatusCode ? ktem.value: '' }}
              </template>
            </span>
          </div>
        </div>
        <div>
          <van-tag plain type="primary">
            <template v-for="ktem in dict.orderType">
              {{ ktem.code === orderData.orderTypeCode ? ktem.value : '' }}
            </template>
          </van-tag>
          <span class="gl_pl_10">
            <van-tag v-if="orderData.isOnlinePayment" plain type="primary">线上支付</van-tag>
            <van-tag v-else plain type="primary">线下支付</van-tag>
          </span>
          <span class="right">￥{{ formatMoney(TotalAmount) }}</span>
        </div>
      </div>
      <van-divider />
    </div>
    <div style="margin-bottom: 80px">
      <van-tabs v-model="active" type="card" color="#1989fa">
        <van-tab title="详细报项">
          <ReportItem :data="report" />
        </van-tab>
        <van-tab title="费用">
          <Cost :data="charges" :order-data="orderData" />
        </van-tab>
      </van-tabs>
    </div>
    <div class="fixed_bottom">
      <div class="space_between cost" @click="showPopup()">
        <p>费用详情</p>
        <p><van-icon name="arrow" /></p>
      </div>
      <van-overlay :show="show" />
      <van-popup v-model="show" :overlay="false" closeable round position="bottom" @click.stop>
        <div style="font-size: 12px; color: #333333" class="gl_padding_20 gl_mt_30">
          <div v-for="(item, index) in summary" :key="index" class="space_between">
            <p>{{ item.ChargeTypeName }}：</p>
            <p style="color: #666666">{{ formatMoney(item.Amount) }}元</p>
          </div>
          <div class="space_between">
            <p>已缴纳费用：</p>
            <p style="color: #666666">{{ formatMoney(PaidAmount) }} 元</p>
          </div>
        </div>
      </van-popup>
      <div class="space_between gl_padding_10 gl_mb_5">
        <div>
          <span style="font-size: 14px">共计：</span>
          <span>￥{{ formatMoney(TotalAmount) }}</span>
        </div>
        <div>
          <van-button v-if="!orderData.isOnlinePayment && offlineData.busCollectionCodeList.length > 0" class="gl_mr_15" style="border-radius: 6px;" type="primary" size="small" @click="showOfflinePayInfo">查看支付码</van-button>
          <van-button v-if="orderData.orderStatusCode == 'WAIT_BUYER_PAY'" style="border-radius: 6px;" size="small" plain type="info" @click="cancelOrder(orderData.orderNo)">取消订单</van-button>
          <van-button v-if="orderData.orderStatusCode == 'WAIT_BUYER_PAY' && orderData.isOnlinePayment" class="gl_ml_15" style="border-radius: 6px; padding:0 32px" size="small" type="info" @click="payment(orderData.orderNo)"> 支付 </van-button>
        </div>
      </div>
    </div>
    <form id="form" ref="form" action="https://unipay.ydfuture.com/api/v1/trade/cashDesk" method="post" style="display:none">
      <input ref="pay_params" type="text" name="pay_params" value="">
      <button type="submit">提交</button>
    </form>
    <!-- 支付码弹出层 -->
    <van-popup v-model="offlineDialogVisible" class="pay_type" style="width:90%">
      <offline-pay-info :offline-data="offlineData" :is-show-btn="false" :is-show-text="false" />
    </van-popup>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import Cost from './cost';
import ReportItem from './reportItem';
import OfflinePayInfo from '@/viewMobile/components/OfflinePayInfo';
import {
  api_GET_TradeOrderDetails,
  api_GET_TradePayOrderParameter, // 去支付
  api_PUT_TradeCancellationOfOrder // 取消订单
} from '@/extend/api/swaggerApi/app.js';
import {
  Api_GET_TradeOrderDetailsQO,
  Api_GET_TradePayOrderParameterQO
} from '@/lib/form/swaggerForm';
export default {
  components: {
    ReportItem,
    Cost,
    OfflinePayInfo
  },
  data() {
    return {
      title: '订单详情',
      gameId: '',
      orderData: {},
      orderDetail: [],
      isPageLoading: false,
      active: '',
      show: false,
      charges: [],
      summary: [],
      TotalAmount: 0,
      PayAmount: 0,
      PaidAmount: 0,
      report: [],
      offlineDialogVisible: false,
      offlineData: {
        busCollectionCodeList: []
      },
      Api_GET_TradeOrderDetailsQO: new Api_GET_TradeOrderDetailsQO(),
      action: 'https://unipay.ydfuture.com/api/v1/trade/cashDesk', // 支付地址
      Api_GET_TradePayOrderParameterQO: new Api_GET_TradePayOrderParameterQO()
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    })
  },
  created() {
    this.gameId = this.$route.params.id;
    this.getDict();
    this.getDetail();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    // 获取订单详情
    getDetail() {
      var that = this;
      this.isPageLoading = true;
      this.Api_GET_TradeOrderDetailsQO.OrderNo = this.$route.query.id;
      api_GET_TradeOrderDetails(this.Api_GET_TradeOrderDetailsQO).then(res => {
        that.orderData = res;
        that.offlineData.busCollectionCodeList = res.busCollectionCodeList || [];
        if (res.details) {
          that.orderDetail = JSON.parse(res.details);
          that.TotalAmount = that.orderDetail.TotalAmount;
          that.PayAmount = that.orderDetail.PayAmount;
          that.PaidAmount = that.orderDetail.PaidAmount;
          that.charges = that.orderDetail.Charges;
          that.summary = that.orderDetail.Summary;
          that.report = that.charges.filter((item) => {
            return item.Code === 'Entry';
          });
        }
        console.log(that.orderDetail, 'dd');
        that.isPageLoading = false;
      }).catch(() => {
        that.isPageLoading = false;
      });
    },
    // 显示支付码
    showOfflinePayInfo() {
      this.offlineDialogVisible = true;
    },
    // 取消订单
    cancelOrder(id) {
      var that = this;
      that.$dialog.confirm({
        message: '您确定要取消该订单吗？'
      }).then(() => {
        const data = { orderNo: id };
        api_PUT_TradeCancellationOfOrder(data).then(res => {
          that.$notify({ type: 'success', message: '取消成功' });
          that.getDetail();
        }).catch(() => {
          that.$notify({ type: 'error', message: '取消失败' });
        });
      }).catch(() => {
        that.$notify({ type: 'primary', message: '放弃取消' });
      });
    },
    // 去支付
    payment(id) {
      var that = this;
      if (id) {
        // var href = window.location.href;
        // var url = href.split('?');
        const _origin = window.location.origin;
        const _pathname = window.location.pathname;
        const _orderUrl = '#/myCenter/order';
        const url = _origin + _pathname + _orderUrl;
        that.Api_GET_TradePayOrderParameterQO.OrderNo = id;
        that.Api_GET_TradePayOrderParameterQO.ReturnUrl = url; // 支付成功后跳转的地址
        api_GET_TradePayOrderParameter(that.Api_GET_TradePayOrderParameterQO).then(res => {
          that.$refs.pay_params.value = res.parameter.replace(/\s*/g, '');
          that.$refs.form.submit();
        }).catch(error => {
          this.$toast.fail(`${error.error.message}`);
        });
      }
    },
    // 格式化货币格式 （分）
    formatMoney(num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    },
    onSubmit(id) {
      var that = this;
      if (id) {
        var url = window.location.href;
        that.Api_GET_TradePayOrderParameterQO.OrderNo = id;
        that.Api_GET_TradePayOrderParameterQO.ReturnUrl = url; // 支付成功后跳转的地址
        api_GET_TradePayOrderParameter(that.Api_GET_TradePayOrderParameterQO)
          .then(res => {
            that.$refs.pay_params.value = res.parameter.replace(/\s*/g, '');
            that.$refs.form.submit();
          }).catch(() => {});
      }
    },
    // 显示费用详情
    showPopup() {
      this.show = !this.show;
    },
    // 图片回显
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 返回上一层
    goBack() {
      this.$router.push({
        path: `/myCenter${this.gameId && '/' + this.gameId || ''}/order`
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.order {
  position: relative;
}
.order_img {
  width: 60px;
  height: 60px;
  border: 1px solid #DCDFE6;
  display: inline-block;
  border-radius: 6px;
  overflow: hidden;
  vertical-align: middle;
}
.order_text {
  line-height: 28px;
  // height: 100px;
  width: 74%;
  vertical-align: middle;
  display: inline-block;
  font-size: 14px;
}
.order_name {
  width: 205px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.space_between {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.order_operation {
  height: 34px;
}
.order_detail {
  background: rgba(247, 247, 247, 1);
  border-radius: 4px;
  padding: 10px;
  position: relative;
  .order_img {
    border-radius: 30px;
  }
}
.detail {
  font-size: 14px;
  line-height: 20px;
  color: #666666;
}
.order_span {
  font-weight: 400;
  color: #9D9D9D;
  font-size: 12px;
}
.amount {
  font-size: 12px;
  display: inline-flex;
  flex-wrap: wrap;
}
.right {
  float: right;
}
.cost {
  background: #fff7cc;
  font-size: 14px;
  padding: 5px 10px;
}
.fixed_bottom {
  width: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 999;
  background: #fff;
  border-radius: 16px 16px 0 0;
}
.van-overlay {
  height: calc(100% - 90px);
}
.van-popup {
  max-height: calc(100% - 88px);
}
.van-popup--bottom {
  bottom: 88px;
}
</style>
